package com.app.sv.ywms.kc

import com.app.exception.BusinessException
import com.app.pub.billtype.PubBilltype
import com.app.ywms.kc.Ycrkmx
import com.app.ywms.kc.Yonhandnum

class YonhandnumService {
    static transactional = true
    def saveYcrkmx(Ycrkmx hand){

            if(!hand.validate()){

                log.error(hand.errors)
                 throw  new BusinessException('出入库明细校验错误！')
            }
            hand.save()
           //更新现存量
            updateHandNum([hand],false)



    }

    def deleteYcrkmx(String sourcebid,PubBilltype billtype){
        def mx=  Ycrkmx.findBySourceBidAndSourceBillType(sourcebid,billtype)


         deleteYcrkmx(mx);
    }

    def deleteYcrkmx(Ycrkmx hand){
        hand.delete()
        //更新现存量
        updateHandNum([hand],true)
    }


    /**
     * 查询现存量

     * @return
     */
    def queryHandNum(def corp,def invmandoc,def pc,def gh,def hz){
        def hands=  Yonhandnum.executeQuery(""" select   bdCorp,invmandoc,hz,gh, sum(sl) from Yonhandnum where bdCorp=?
and invmandoc=?
and pc=?
and hz=?
and gh=?
group by bdCorp,invmandoc,pc,hz,gh
""",
                [corp,invmandoc,pc,hz,gh])
        if(hands?.size()==0) return null;
        return hands

    }

    /**
     *
     * @param corp
     * @param invmandoc
     * @param invbasdoc
     * @param vlot
     * @param warehouse
     * @param calbody
     * @param astunit
     * @param hsl
     * @param dvalidate
     * @param cubasdoc
     * @return
     */
   private Yonhandnum getIcOnhandnum (def bdCorp,def invmandoc,def pc,def hz,gh,ht){
	  //根据条件查询现存量

    return Yonhandnum.findOrCreateWhere(bdCorp: bdCorp,invmandoc:invmandoc,hz:hz,pc:pc,gh: gh,ht: ht)

}


    /**
     *
     * @param header
     * @param callback      是否是反操作
     * @return
     * @throws BusinessException
     */
    def updateHandNum( mxs,Boolean callback){



        mxs.each {



            Yonhandnum num=this.getIcOnhandnum(it.bdCorp, it.invmandoc, it.pc, it.hz,it.gh,it.ht);

            if(num.isAttached())
                num.lock()
            if(callback)
            {
                num.sl=num.sl-it.insl+it.outsl

                if(num.sl<0){
                    throw new BusinessException("现存量为负")
                }
            }else{
                num.sl=num.sl+it.insl-it.outsl

                if(num.sl<0){
                    throw new BusinessException("现存量为负")
                }
            }

          if(!num.validate()){
              log.error(num.errors)
              throw new BusinessException('现存量表更新时数据校验错误！');
          }


            num.save()


        }



    }

}
